import Cookies from 'js-cookie'
import { MESSAGE_EVENT_TYPE } from '@/api'

export default function useReceiveMessage() {
  const token = Cookies.get('token')
  const auth = ref(!!token)
  function receiveMessage(evt: MessageEvent) {
    const origin = window.location.origin
    const fromParent = import.meta.env.VITE_POST_MESSAGE_ORIGIN || origin
    if (fromParent) {
      const { type, message } = evt.data
      console.log(`[iframe] receive token from [${fromParent}].`)
      if (type === MESSAGE_EVENT_TYPE.LOGIN_SUCCESS) {
        Cookies.set('token', message.token)
      }
    }
    auth.value = true
  }

  function addListener() {
    window.addEventListener('message', receiveMessage, false)
  }

  onBeforeUnmount(() => {
    window.removeEventListener('message', receiveMessage)
  })

  return {
    receiveMessage,
    addListener,
    auth,
  }
}
